package com.flying.client.network;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.flying.client.network.msg.ORMsg;
import com.flying.client.utils.Logger;

public class MsgDecoder extends FrameDecoder{
	private static final Logger logger = Logger.getLogger(MsgDecoder.class.getName());
	
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		
		logger.debug("decode canread="+buffer.readableBytes());
		//记录当前读取位置
		buffer.markReaderIndex();
		
		if (buffer.readableBytes() < ORMsg.MSG_HEADER_LEN)
		{
			return null;
		}
		
		short msgType = buffer.readShort();
		short msgSeq = buffer.readShort();
		int msglen = buffer.readInt();
		
		logger.debug("msgid=" + msgType + "msgSeq=" + msgSeq + " msglen="+msglen);
		
		if (buffer.readableBytes() < msglen)
		{
			buffer.resetReaderIndex();
			return null;
		}
		
		ORMsg msg = new ORMsg(msgType,msgSeq,buffer.readBytes(msglen));
		
		return msg;
	}
}
